//
//  CacheVC.m
//  ProjectforHDX
//
//  Created by yinda on 2018/6/4.
//  Copyright © 2018年 H.DX. All rights reserved.
//

#import "CacheVC.h"
#import "PlateModel.h"
#import "WCheckgoodsCell.h"
#import "WCheckgoodsBbottomV.h"
#import "MHScanViewController.h"
#import "CustomNavigationController.h"
#import "WCStroehouse.h"
#import "WCheckgoodsTopView.h"
#import "WCheckgoodsTitleView.h"
#import "PlateModel.h"
#import "CunjianDetailVC.h"
#import "PartsItemV.h"
#import "BDAlertView.h"
#import "ManuallyaddVC.h"

#define PLATESERIA  @"点击扫码"
#define PLATECODE  @"点击扫码"

@interface CacheVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

/*
 *扫描获取的条形码
 */
@property (nonatomic, copy) NSString *code;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *platesArr;

@property (nonatomic, strong) NSMutableArray *platesDicArr;

@property (nonatomic, strong) NSMutableArray *detailArr;  //确认存件的数组用于传递

@property (nonatomic, strong) NSMutableArray *boxcodeArr;  //箱号数组1

@property (nonatomic, strong) NSMutableArray *boxIDArr;  //箱子ID数组

@property (nonatomic, strong) NSMutableArray *tagetboxcodeArr;  //箱子数组2

@property (nonatomic, strong) WCheckgoodsTopView *topView;
@property (nonatomic, strong) WCheckgoodsTopView *headerView;
@property (nonatomic, strong) WCheckgoodsBbottomV *bottomView;



//@property (nonatomic, strong)WCStroehouse *house;
@property (nonatomic, copy)NSString *cargoSpace;
@property (nonatomic, copy)NSString *cargoSpaceID;
@property (nonatomic, assign)BOOL isChange;




@end

@implementation CacheVC

static NSString *mainTableCell_ID = @"mainHandleTableCell";

-(NSMutableArray *)platesDicArr
{
    if (!_platesDicArr) {
        _platesDicArr = [NSMutableArray array];
    }
    return _platesDicArr;
}

-(NSMutableArray *)platesArr
{
    if (!_platesArr) {
        _platesArr = [NSMutableArray array];
    }
    return _platesArr;
}

-(NSMutableArray *)detailArr
{
    if (!_detailArr) {
        _detailArr = [NSMutableArray array];
    }
    return _detailArr;
}

-(void)viewDidLoad{
    [super viewDidLoad];
//    THUserInfoModel *model = [THMangerTool getAccountInfo];
//    if ([model.userType isEqualToString:@"2"]||[model.userType isEqualToString:@"3"]) {
        self.rightItem.hidden=NO;
        [self.rightItem setTitle:[UtilCheck language:@"PickUpVC.Barcodeblur"] forState:0];
        [self.rightItem setImage:BDFILEIMAGENAEM(@"Home/btn_msgNoticesss") forState:UIControlStateNormal];
//    }
    [self  setupView];
    
    
    //    [self loadData];
}

-(int)convertToInt:(NSString*)strtemp {
    
    int strlength = 0;
    char* p = (char*)[strtemp cStringUsingEncoding:NSUnicodeStringEncoding];
    for (int i=0 ; i<[strtemp lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
    }
    return (strlength+1)/2;
    
}

#pragma mark 底部按钮点击
-(void)setupView
{
    self.isChange = NO;
    self.platesArr = [[NSMutableArray alloc]init];
    self.detailArr = [NSMutableArray new];
    self.labnav.text = [self.type isEqualToString:@"1"]?[UtilCheck language:@"CachVC.cunjianNice"]:[UtilCheck language:@"CachVC.cunjianbad"];
    [self.labnav setFont:NavFontSize];
    [self.labnav setTextColor:[UIColor whiteColor]];
    self.cargoSpaceID = @"";
    self.cargoSpace = @"";
    self.view.backgroundColor = [UIColor whiteColor];
    
    UITableView *tableView = [[UITableView alloc]init];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView setFrame:CGRectMake(0, 80, SCREEN_WIDTH, SCREEN_HEIGHT-200)];
    [self.view addSubview:tableView];
    
    self.headerView = [[WCheckgoodsTopView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    self.topView = _headerView;
    [_headerView setPlateCount:self.platesArr.count];
    [self.view addSubview:_headerView];
    
    WCheckgoodsTitleView *titleView = [[WCheckgoodsTitleView alloc]initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, 40)];
    titleView.isCunOrQu = YES;
    [self.view addSubview:titleView];
    
    
    _bottomView = [[WCheckgoodsBbottomV alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-120, SCREEN_WIDTH, 60)];
    _bottomView.isCunOrquJian = YES;
    _bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_bottomView];
    
    __weak typeof(self) weakSelfs = self;
    
    _bottomView.Bottomblock = ^(long tag){
        
        switch (tag) {
            case 5: //下一步跳到详情
            {
                if (self.platesArr.count == 0 || self.detailArr.count<1) {
                    [[BDHUD sharedManager]showWords:[UtilCheck language:@"HUD.pleasesacn"]];
                    break;
                }
                NSInteger nums=0;
                for (NSDictionary *dic in weakSelfs.detailArr) {
                    nums = nums + [dic[@"number"]integerValue];
                }
//                [self finishedCheck];
                CunjianDetailVC *cunVC = [[CunjianDetailVC alloc]init];
                cunVC.partArr = weakSelfs.detailArr;
                cunVC.serialNumber = weakSelfs.serialNumber;
                cunVC.titlename = [UtilCheck language:@"order.cundetail"];
                cunVC.isQujian = @"0";
                cunVC.number = nums;
                [weakSelfs.navigationController pushViewController:cunVC animated:YES];
                 
            }
                break;
            case 1: //扫描二维码
            {
                
//                if (self.cargoSpace == nil || self.cargoSpace.length < 1) {
//                    [Toolobject showTextWithMessage:[UtilCheck language:@"HUD.pleaseScnCCargo"]];
//                    break;
//                }
                if (self.detailArr.count>=[self.freenumber integerValue]) {
                    [Toolobject showAlterwithMessage:[UtilCheck language:@"CachVC.Quantitylimit"]];
                    return ;
                }
                 weakSelfs.bottomView.isCunOrquJian = NO;
                
                MHScanViewController *scanVC = [[MHScanViewController alloc]init];
                __weak typeof(self) weakSelf = weakSelfs;
                scanVC.isdismiss = YES;
                scanVC.rebackData = ^(NSString *retStr){
                    
                    for (int i =0; i<self.platesArr.count; i++) {
                        PlateModel *tempModel = weakSelfs.platesArr[i];
                        if ([tempModel.sn isEqualToString:retStr] ) {
                            [[BDHUD sharedManager]showWords:[UtilCheck language:@"HUD.hasScanPlate"]];
                            return ;
                        }
                    }
                    
                    [weakSelf getPartInfoWithQRCode:retStr];
                    
                    
                };
                CustomNavigationController *vc = [[CustomNavigationController alloc]initWithRootViewController:scanVC];
                [weakSelfs presentViewController:vc animated:YES completion:^{
                    
                }];
                
            }
                break;
                
#pragma mark 点击一维码按钮添加一行
            case 2: //扫描一维码,添加一个cell
            {
                if (weakSelfs.detailArr.count>=[weakSelfs.freenumber integerValue]) {
                    [Toolobject showAlterwithMessage:[UtilCheck language:@"HUD.hasScanPlate"]];
                    return ;
                }
                 weakSelfs.bottomView.isCunOrquJian = NO;
//                if (self.cargoSpace == nil || self.cargoSpace.length < 1) {
//                    [Toolobject showTextWithMessage:[UtilCheck language:@"HUD.pleaseScnCCargo"]];
//                    return;
//                }
                
                
                PlateModel *tempModel = [[PlateModel alloc]init];
                tempModel.sn = PLATESERIA;
                tempModel.code = PLATECODE;
                tempModel.containerNo = weakSelfs.boxcode;
                [weakSelfs.platesArr addObject:[THMangerTool deepCopy:tempModel]];
                
                
                NSMutableDictionary *data = [[NSMutableDictionary alloc]init];
                [data setValue:weakSelfs.boxcode forKey:@"containerNo"];
                [data setValue:@"" forKey:@"code"];
                [data setValue:@"" forKey:@"sn"];
                [data setValue:@"" forKey:@"exception"];
                
                [weakSelfs.platesDicArr addObject:[THMangerTool deepCopy: data]];
                [weakSelfs.platesDicArr addObject:[THMangerTool deepCopy:tempModel]];
                
                [weakSelfs.tableView reloadData];
                
                
            }
                break;
            case 6:// 换箱
            {
                if (weakSelfs.isChange==NO) {
                    [weakSelfs changeBox];
                    //                 [Toolobject showAlterwithMessage:@"请先关闭当前箱子，才能进行换箱操作"];
                }
            }
                break;
//            case 6: //扫描库位
//            {
//
//                MHScanViewController *scanVC = [[MHScanViewController alloc]init];
//                scanVC.isdismiss = YES;
//
//                scanVC.rebackData = ^(NSString *retStr){
//                    NSLog(@"%@",retStr);
//
//                    [self getContainInfoWith:retStr];
//
//                };
//                CustomNavigationController *vc = [[CustomNavigationController alloc]initWithRootViewController:scanVC];
//                [self presentViewController:vc animated:YES completion:^{
//
//                }];
//
//
//
//            }
//                break;
                
                
            default:
                break;
        }
    };
}

// 进入手动添加板件
-(void)rightItem:(RZCustomButtom *)sender{
    if (self.detailArr.count>6) {
        [Toolobject showAlterwithMessage:[UtilCheck language:@"CachVC.Deleteboard"]];
        return;
    }
    ManuallyaddVC *vc = [[ManuallyaddVC alloc]init];
    vc.cabinetCode = self.cabinetCode;
    vc.boxcode = self.boxcode; // 箱号
    vc.boxID = self.boxID; // 箱号ID
    vc.freenumber = self.freenumber; // 空余数量
    vc.serialNumber = self.serialNumber; // 流水号
    vc.type = self.type;
    vc.operationType = @"1";
    vc.checkArr = self.detailArr;
     [self.navigationController pushViewController:vc animated:YES];
}

// 箱子列表接口
- (void)requestboxListData{
    NSString *key = [THMangerTool getKey];
    NSDictionary *parmes = @{@"cabinetCode":self.cabinetCode,@"key":key,@"type":self.type};
    self.boxIDArr = [NSMutableArray new];
    self.boxcodeArr = [NSMutableArray new];
    self.tagetboxcodeArr = [NSMutableArray new];
    [AFHttpTool postJsonDatawithUrl:@"getBox" parameters:parmes success:^(id responseObject) {
        if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
            NSArray *dataArr =[responseObject objectForKey:@"data"];
            
            if (dataArr.count>0) {
                for (NSDictionary *dic in dataArr) {
                    NSString *boxCodeStr = [NSString stringWithFormat:@"%@号箱(%@)",dic[@"boxCode"],dic[@"col1"]];
                    [self.boxcodeArr addObject:boxCodeStr];
                    [self.tagetboxcodeArr addObject:dic[@"boxCode"]];
                    [self.boxIDArr addObject:dic[@"boxID"]];
                }
                [self.boxcodeArr addObject:@"随机"];
                [self.boxIDArr addObject:@""];
            }
        }
    } fail:^(id responseObject, NSError *error) {
        
    }];
}

#pragma mark 换箱操作
- (void)changeBox{
    if (self.boxcodeArr.count>0) {
        [BDAlertView showAlertWithTitle:[UtilCheck language:@"PickUpVC.selectBoxCode"] isChoice:NO otherTitles:self.boxcodeArr completion:^(BOOL cancelled, NSInteger selectedIndex) {
            if (selectedIndex==-1) {
                return ;
            }
            NSString *key = [THMangerTool getKey];
            NSString *targetboxcode = self.tagetboxcodeArr[selectedIndex];
            NSString *targetboxId = self.boxIDArr[selectedIndex];
            if ([targetboxcode isEqualToString:@"随机"]) {
                targetboxcode = @"";
            }
            NSDictionary *parmes =  @{@"cabinetCode":self.cabinetCode,@"boxID":self.boxID,@"boxCode":self.boxcode,@"key":key,@"type":self.type,@"targetBoxCode":targetboxcode,@"targetBoxID":targetboxId};
            [[BDHUD sharedManager] showBDHUD:self.view title:[THMangerTool language:@"HUD.title"]];
            [AFHttpTool postJsonDatawithUrl:@"changeBox" parameters:parmes success:^(id responseObject) {
                [[BDHUD sharedManager] dismissHUD:self.view];
                if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
                    [Toolobject showAlterwithMessage:[UtilCheck language:@"CachVC.SuccessfulchangeBox"]];
                    if ([[responseObject objectForKey:@"data"]objectForKey:@"boxCode"]!=nil) {
                        self.boxcode = [[responseObject objectForKey:@"data"]objectForKey:@"boxCode"]; // 箱号
                        self.boxID = [[responseObject objectForKey:@"data"]objectForKey:@"boxID"]; // 箱号ID
                        self.freenumber = [[responseObject objectForKey:@"data"]objectForKey:@"number"]; // 空余数量
                        self.serialNumber = [[responseObject objectForKey:@"data"]objectForKey:@"serialNumber"]; // 流水号
                    }
                }
                else{
                    [Toolobject showAlterwithMessage:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                }
            } fail:^(id responseObject, NSError *error) {
                 [[BDHUD sharedManager] dismissHUD:self.view];
            }];
        }];
    }
    else{
        [Toolobject showAlterwithMessage:[UtilCheck language:@"PickUpVC.nochangeBoxCode"]];
    }

}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self  requestboxListData];
    NSArray *shoudongDetailArr = [[NSUserDefaults standardUserDefaults]objectForKey:@"shoudongDetailArr"];
    if (shoudongDetailArr!=nil&&shoudongDetailArr.count>0) {
        PlateModel *model = [[PlateModel alloc]init];
        NSDictionary *data = shoudongDetailArr.firstObject;
        model.containerNo = self.boxcode;
        model.sn = [data objectForKey:@"partSN"];
        //                model.code = [data objectForKey:@"partCode"];
        model.code = [data objectForKey:@"partCode"];
        model.version = [data objectForKey:@"partVersion"];
        model.name = [data objectForKey:@"partName"];
        model.number = @"1";
        [self.platesArr addObject:model];
        [self.detailArr addObjectsFromArray:shoudongDetailArr];
        [_tableView reloadData];
    }
    
    if (self.platesArr.count < 1) {
        [[BDHUD sharedManager] showNOneDataViewHUD:self.tableView top:60 title:[THMangerTool language:@"HUD.noData"] onClick:^{
        }];
        
    }else{
        [[BDHUD sharedManager] dismissHUD];
    }
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    // 移除手动添加的板件
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"shoudongDetailArr"];
}

#pragma -mark 点击事件  ---扫描一维码序列号

- (void)touchPlateSeria:(UITapGestureRecognizer *)recognizer{
    
   
    long index = recognizer.view.tag - 2000;
    PlateModel *tempModel = self.platesArr[index];
    
    if (tempModel.code == nil || [tempModel.code isEqualToString:@""] || [tempModel.code isEqualToString:PLATECODE]) {
        [Toolobject showAlterwithMessage:[UtilCheck language:@"CachVC.ScanPlatCode"]];
        return;
    }
    
    
    MHScanViewController *scanVC = [[MHScanViewController alloc]init];
    __weak typeof(self) weakSelf = self;
    scanVC.isdismiss = YES;
    scanVC.rebackData = ^(NSString *retStr){

        if ([retStr isEqualToString:@"DUMMY"]) {
            tempModel.sn = retStr;
            [self getPartInfoWithBarCode:retStr andModel:tempModel andIndex:index];
        }
        else{
             NSArray * array = [NSArray arrayWithArray:weakSelf.platesArr];
            NSInteger a = 0;
            for (PlateModel *testmodel in array) {
                if ([testmodel.sn isEqualToString:retStr]&&[testmodel.code isEqualToString:self.code]) {
                    [Toolobject showAlterwithMessage:[UtilCheck language:@"CachVC.Repeatscan"]];
                    [self.platesArr removeObjectAtIndex:index];
                     [_headerView setPlateCount:weakSelf.platesArr.count];
                    a = 1;
                     [weakSelf.tableView reloadData];
                }
            }
            if (a!=1) {
                tempModel.sn = retStr;
                [self getPartInfoWithBarCode:retStr andModel:tempModel andIndex:index];
            }
        }
    };
    CustomNavigationController *vc = [[CustomNavigationController alloc]initWithRootViewController:scanVC];
    [self presentViewController:vc animated:YES completion:^{
        
    }];
    
}

#pragma -mark 点击事件  ---扫描一维码板件号

- (void)touchPlateNo:(UITapGestureRecognizer *)recognizer{
    long index = recognizer.view.tag - 1000;
    
    MHScanViewController *scanVC = [[MHScanViewController alloc]init];
    __weak typeof(self) weakSelf = self;
    scanVC.isdismiss = YES;
    scanVC.rebackData = ^(NSString *retStr){
        
        PlateModel *tempModel = self.platesArr[index];
        NSArray * array = [NSArray arrayWithArray:self.detailArr];
        if (![tempModel.sn isEqualToString:PLATESERIA]) {
            for (NSDictionary *dic in array) {
                if ([tempModel.sn isEqualToString:dic[@"partSN"]]&&[tempModel.code containsString:dic[@"partCode"]]) {
                    [self.detailArr removeObject:dic];
                    [weakSelf.platesArr removeObject:tempModel];
                    [_headerView setPlateCount:self.platesArr.count];
//                    [weakSelf.platesDicArr removeObjectAtIndex:index];
                     [Toolobject showAlterwithMessage:[UtilCheck language:@"CachVC.UnkonowCode"]];
                    break;
                }
            }
        }
        else{
        tempModel.code = retStr;
        self.code = retStr;
        [weakSelf.platesArr replaceObjectAtIndex:index withObject:tempModel];
        
        NSMutableDictionary *dict =  weakSelf.platesDicArr[index];
        [dict setValue:retStr forKey:@"code"];
        [weakSelf.platesDicArr replaceObjectAtIndex:index withObject:dict];
        }
        [self.tableView reloadData];

    };
    CustomNavigationController *vc = [[CustomNavigationController alloc]initWithRootViewController:scanVC];
    [self presentViewController:vc animated:YES completion:^{
        
    }];
    
}

#pragma -mark 盘点完成
-(void)finishedCheck
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
    fmt.dateFormat = @"YYYY-MM-dd HH:mm:ss";
    NSString *checkStartTime = [fmt stringFromDate:now];
    params[@"checkStartTime"] = checkStartTime;
    params[@"inventory"] = self.platesDicArr;
    
//    [AFHttpTool postJsonDatawithUrl:@"/checkRecord" parameters:[params mutableCopy] success:^(id responseObject) {
//        if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
//            if([[responseObject objectForKey:@"data"] isKindOfClass:[NSDictionary class]]){
//                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
//                [self.navigationController popViewControllerAnimated:YES];
//            }
//            else{
//                //返回数据出问题 弹出服务器返回信息
//                if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
//                    [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
//                }
//                else{
//                    [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
//                }
//            }
//
//        }
//        else{
//            //返回数据出问题 弹出服务器返回信息
//            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
//                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
//            }
//            else{
//                [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
//            }
//        }
//    } fail:^(id responseObject, NSError *error) {
//        [[BDHUD sharedManager] dismissHUD];
//        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
//            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
//        }else {
//            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
//        }
//    }];
    
}

#pragma -mark 二维码获取板件信息
- (void)getPartInfoWithQRCode:(NSString *) codeStr{
    if ([codeStr containsString:@"u0004"]) {
        codeStr = [UtilCheck stringreplace:codeStr Replace:@"u0004" Target:@""];
    }
    if ([codeStr containsString:@"u001e"]) {
        codeStr = [UtilCheck stringreplace:codeStr Replace:@"u001e" Target:@""];
    }
    if ([codeStr containsString:@"u001d"]) {
        codeStr = [UtilCheck stringreplace:codeStr Replace:@"u001d" Target:@""];
    }
    if (self.type==nil) {
        return;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSLog(@"%@",codeStr);
//    params[@"containerCode"] = self.house.houseId;
    params[@"code"] = codeStr;
    NSString *key = [THMangerTool getKey];
    [params setObject:key forKey:@"key"];
    [params setObject:self.type forKey:@"type"];
    [params setObject:@"1" forKey:@"operationType"];
    [params setObject:self.cabinetCode forKey:@"cabinetCode"];
     [[BDHUD sharedManager] showBDHUD:self.view title:[THMangerTool language:@"HUD.title"]];
    [AFHttpTool postJsonDatawithUrl:@"getPartInfo2_1_2" parameters:[params mutableCopy] success:^(id responseObject) {
        
        if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
            
            if([[responseObject objectForKey:@"data"] isKindOfClass:[NSDictionary class]]){
                NSMutableDictionary *data = [responseObject objectForKey:@"data"];
//                data[@"containerNo"] = self.house.name;
                [data setValue:@"1" forKey:@"number"];
                [self.platesDicArr addObject:data];
                
//                // 校验是否重复扫描
//                NSArray * array = [NSArray arrayWithArray:self.platesArr];
//                for (PlateModel *testmodel in array) {
//                    if ([testmodel.sn isEqualToString:[data objectForKey:@"partSN"]]&&[testmodel.code isEqualToString:[data objectForKey:@"partCode"]]) {
//                        [Toolobject showAlterwithMessage:[UtilCheck language:@"CachVC.Repeatscan"]];
//                        return ;
//                    }
//                }
                
                [data setObject:self.boxcode forKey:@"boxCode"]; //箱号
                [data setObject:self.boxID forKey:@"boxID"]; //箱号ID
                [data setObject:self.cabinetCode forKey:@"cabinetCode"]; //货位编号
                [data setObject:@"" forKey:@"cargoSpace"]; //货位号
                [data setObject:self.type forKey:@"partType"];
                [self.detailArr addObject:data];
                 self.isChange = YES;
                
                PlateModel *model = [[PlateModel alloc]init];
//                model.containerNo = self.house.name;
                model.sn = [data objectForKey:@"partSN"];
                model.code = [data objectForKey:@"partCode"];
                model.version = [data objectForKey:@"partVersion"];
                model.name = [data objectForKey:@"partName"];
                model.containerNo = self.boxcode;
                model.number = @"1";
                
                [self.platesArr addObject:[THMangerTool deepCopy:model]];
                [self.headerView setPlateCount:self.platesArr.count];
                [self.tableView reloadData];
                
                if (self.platesArr.count < 1) {
                    [[BDHUD sharedManager] showNOneDataViewHUD:self.tableView top:60 title:[THMangerTool language:@"HUD.noOrderData"] onClick:^{
                    }];
                    
                }else{
                    [[BDHUD sharedManager] dismissHUD:self.tableView];
                }
                
                [[BDHUD sharedManager]dismissHUD];
            }
            else{
                
                //返回数据出问题 弹出服务器返回信息
                if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
//                     [Toolobject showAlterwithMessage:@"没有找到该板件信息"];
                    [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                }
                else{
                    [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
                }
            }
            
        }
        else{
            
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
            else{
                [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
            }
            
        }
    } fail:^(id responseObject, NSError *error) {
        
        
        
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
    }];
    
}

//一维码扫描板件获取数据
-(void)getPartInfoWithBarCode:(NSString *)code andModel:(PlateModel *)model andIndex:(long) index;
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (self.type==nil) {
        return;
    }
//    params[@"containerCode"] = self.house.houseId;
    params[@"code"] = code;
    params[@"plateCode"] = model.code;
    params[@"plateSN"] = model.sn;
    [params setObject:self.type forKey:@"type"];
    [params setObject:@"1" forKey:@"operationType"];
    NSString *key = [THMangerTool getKey];
    [params setObject:key forKey:@"key"];
    [params setObject:self.cabinetCode forKey:@"cabinetCode"]; // 智能柜编号
     [[BDHUD sharedManager] showBDHUD:self.view title:[THMangerTool language:@"HUD.title"]];
    [AFHttpTool postJsonDatawithUrl:@"getPartInfo1_1_2" parameters:[params mutableCopy] success:^(id responseObject) {
        
        if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
            if([[responseObject objectForKey:@"data"] isKindOfClass:[NSDictionary class]]){
                NSMutableDictionary *data = [responseObject objectForKey:@"data"];
                data[@"containerNo"] = self.boxcode;
                [self.platesDicArr  replaceObjectAtIndex:index withObject:data];
                
                PlateModel *model = [[PlateModel alloc]init];
                model.containerNo = self.boxcode;
                model.sn = [data objectForKey:@"partSN"];
//                model.code = [data objectForKey:@"partCode"];
                model.code = self.code;
                model.version = [data objectForKey:@"partVersion"];
                model.name = [data objectForKey:@"partName"];
                model.number = @"1";
                
                [data setObject:@1 forKey:@"number"]; 
                [data setObject:self.boxcode forKey:@"boxCode"]; //箱号
                [data setObject:self.boxID forKey:@"boxID"]; //箱号ID
                [data setObject:self.cabinetCode forKey:@"cabinetCode"]; //货位编号
                [data setObject:self.boxID forKey:@"cargoSpace"]; //货位号
                [data setObject:[NSNumber numberWithInt:[self.type intValue]] forKey:@"partType"];
                if (self.detailArr.count>index) {
                    [self.detailArr replaceObjectAtIndex:index withObject:data];
                }
                else{
                [self.detailArr addObject:data];
                    self.isChange = YES;
                }
            
                [self.platesArr replaceObjectAtIndex:index withObject:[THMangerTool deepCopy: model]];
                [self.headerView setPlateCount:self.platesArr.count];
                [self.tableView reloadData];
                
                if (self.platesArr.count < 1) {
                    [[BDHUD sharedManager] showNOneDataViewHUD:self.tableView top:60 title:[THMangerTool language:@"HUD.noOrderData"] onClick:^{
                    }];
                    
                }else{
                    [[BDHUD sharedManager] dismissHUD:self.tableView];
                }
                
                [[BDHUD sharedManager]dismissHUD];
            }
            else{
//                [Toolobject showAlterwithMessage:@"获取板件信息失败，请重新扫描序列号"];
                
                
                //返回数据出问题 弹出服务器返回信息
                if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
//                    [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                    [self.platesArr removeObjectAtIndex:index];
                    [self.headerView setPlateCount:self.platesArr.count];
                    if (self.detailArr.count>index) {
                        [self.detailArr removeObjectAtIndex:index];
                    }
                    [Toolobject showAlterwithMessage:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                    [self.tableView reloadData];
                }
                else{
                    [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
                }
            }
        }
        
        else{
//            [Toolobject showAlterwithMessage:@"获取板件信息失败，请重新扫描序列号"];
            
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
//                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                 [self.platesArr removeObjectAtIndex:index];
                [self.headerView setPlateCount:self.platesArr.count];
                if (self.detailArr.count>index) {
                    [self.detailArr removeObjectAtIndex:index];
                }
                 [Toolobject showAlterwithMessage:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                 [self.tableView reloadData];
            }
            else{
                [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
            }
            
        }
    } fail:^(id responseObject, NSError *error) {
        
        
//        [Toolobject showAlterwithMessage:@"获取板件信息失败，请重新扫描序列号"];
        
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
    }];
    
}


#pragma -mark 从网络获取货位
-(void)getContainInfoWith:(NSString *)str
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"code"] = str;
    NSString *key = [THMangerTool getKey];
    [params setObject:key forKey:@"key"];
    [AFHttpTool postJsonDatawithUrl:@"getCargoSpace" parameters:[params mutableCopy] success:^(id responseObject) {
        if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
            if([[responseObject objectForKey:@"data"] isKindOfClass:[NSDictionary class]]){
                NSDictionary *data=[responseObject objectForKey:@"data"];
                WCStroehouse *store = [[WCStroehouse alloc]init];
                // 货位号
                self.cargoSpace = [data objectForKey:@"cargoSpace"];
                // 货位ID
                self.cargoSpaceID = [data objectForKey:@"cargoSpaceID"];
                [store setValuesForKeysWithDictionary:data];
                [self.topView setStroeInfo:store];
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
//                self.house = store;
            }
            else{
                //返回数据出问题 弹出服务器返回信息
                if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                    [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                }
                else{
                    [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.nothing"]];
                }
            }
            
        }
        else{
            //返回数据出问题 弹出服务器返回信息
            if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
            }
            else{
                [[BDHUD sharedManager] showWords:[THMangerTool language:@"HUD.noCheck"]];
            }
            
        }
    } fail:^(id responseObject, NSError *error) {
        [[BDHUD sharedManager] dismissHUD];
        if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
        }else {
            [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
        }
        
    }];
    
    
}



#pragma -mark tableView datasource delegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WCheckgoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WCheckgoodsCell"];
    if (!cell) {
        cell = [[WCheckgoodsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"WCheckgoodsCell"
                ];
    }
    HOST;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setPlateModle:self.platesArr[indexPath.row]];
    
    UITapGestureRecognizer *plateNoRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(touchPlateNo:)];
    cell.plateNo.tag = 1000 + indexPath.row ;
    plateNoRecognizer.view.tag = cell.plateNo.tag;
    [cell.plateNo addGestureRecognizer:plateNoRecognizer];
    cell.plateNo.userInteractionEnabled = YES;
    
    
    UITapGestureRecognizer *plateSeriaRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(touchPlateSeria:)];
    cell.plateSeria.tag = 2000 + indexPath.row ;
    plateSeriaRecognizer.view.tag = cell.plateSeria.tag;
    [cell.plateSeria addGestureRecognizer:plateSeriaRecognizer];
    cell.plateSeria.userInteractionEnabled = YES;
    
    cell.plateNum.tag = 3000 + indexPath.row;
    cell.plateNum.delegate = self;
//    PlateModel *model = self.platesArr[indexPath.row];
//    if (![model.sn isEqualToString:@"DUMMY"]) {
//        cell.plateNum.enabled = NO;
//    }
//    else{
//        cell.plateNum.enabled = YES;
//    }
    cell.plateNum.enabled = NO;
    cell.plateNum.textAlignment = NSTextAlignmentCenter;
    cell.plateNum.borderStyle = UITextBorderStyleNone;
    return cell;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.platesArr.count < 1) {
        [[BDHUD sharedManager] showNOneDataViewHUD:self.tableView top:60 title:[THMangerTool language:@"HUD.noOrderData"] onClick:^{
        }];
        
    }else{
        [[BDHUD sharedManager] dismissHUD:self.tableView];
    }
    
    
    return self.platesArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"当前是第 %ld 个cell",(long)indexPath.row);
    WCheckgoodsCell *cell = [[WCheckgoodsCell alloc]init];
    [cell setPlateModle:self.platesArr[indexPath.row]];
    return cell.height;;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.platesArr removeObjectAtIndex:indexPath.row];
        [self.headerView setPlateCount:self.platesArr.count];
        [self.platesDicArr removeObjectAtIndex:indexPath.row];
        if (self.detailArr.count>indexPath.row) {
            [self.detailArr removeObjectAtIndex:indexPath.row];
        }
        // Delete the row from the data source.
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        if (self.platesArr.count<1) {
            self.bottomView.isCunOrquJian = YES;
        }
        [_tableView reloadData];
    }
}

#pragma mark textfield 代理方法
-(void)textFieldDidEndEditing:(UITextField *)textField{
    long index = textField.tag - 3000;
    PlateModel *tempModel = self.platesArr[index];
    tempModel.number = textField.text;
    if (self.detailArr.count>0) {
        [self.platesArr replaceObjectAtIndex:index withObject: tempModel];
        NSMutableDictionary *dic = self.detailArr[index];
        [dic setObject:textField.text forKey:@"number"];
    }

}

@end
